<template>
	<view>
		<view class="search-contianer">
			<view class="search-bar">
				<uni-search-bar @confirm="search" @input="input" :radius="100" focus="true" cancelButton="none"></uni-search-bar>
			</view>
		</view>
		<view class="sugg-list" v-if="searchResult.length !== 0">
			<view @click="gotoDetail(item)" class="sugg-list-item" v-for="(item,i) in searchResult" :key="i">
				<view class="goods-name">{{item.goods_name}}</view>
				<uni-icons type="arrowright" size="16"></uni-icons>
			</view>
		</view>
		<view class="history-box" v-else>
			<view class="history-title">
				<text>搜索历史</text>
				<uni-icons @click="clean" type="trash" size="17"></uni-icons>
			</view>
			<view class="history-list">
				<uni-tag @click="gotoGoodslist(item)" :text="item" v-for="(item,i) in historyList" :key="i"></uni-tag>
			</view>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				timer:null,
				//获取搜索框的值
				kw:'',
				//搜索结果列表
				searchResult:[],
				//搜索历史列表
				historyList:[]
			};
		},
		onLoad() {
			this.historyList = JSON.parse(uni.getStorageSync('kw') || '[]')
		},
		methods:{
			input(e){
				clearInterval(this.timer)
				 this.timer = setTimeout(() => {
					//console.log(e)
					this.kw = e
					this.getsearchResulList()
					this.savehistory()
				},500)
			},
			async getsearchResulList(){
				if(this.kw.length === 0){
					this.searchResult = []
					return
				}
				const {data:res} = await uni.$http.get('/api/public/v1/goods/qsearch',{query:this.kw})
				if(res.meta.status !== 200){
					return uni.$showMsg()
				}
				this.searchResult = res.message
			},
			//保存搜索历史
			savehistory(){
				this.historyList = [...new Set([this.kw,...this.historyList])]
				//对搜索历史数据进行持久化存储
				uni.setStorageSync('kw',JSON.stringify(this.historyList))
			},
			//点击匹配项跳转到详情页
			gotoDetail(item){
				uni.navigateTo({
					url:'/subpkg/goods_detail/goods_detail?goods_id=' + item.goods_id
				})
			},
			clean(){
				this.historyList = []
				uni.setStorageSync('kw','[]')
			},
			gotoGoodslist(kw){
				uni.navigateTo({
					url:'/subpkg/goods_list/goods_list?query=' + kw
				})
			}
		}
	}
</script>

<style lang="scss">
.search-contianer{
	background-color: #007AFF;
	.search-bar{
		position: sticky;
		top: 0;
		z-index: 999;
	}
}
.sugg-list{
	padding: 0 5px;
	.sugg-list-item{
		display: flex;
		align-items: center;
		justify-content: space-between;
		font-size: 12px;
		padding: 13px 0;
		border-bottom: 1px solid #d5ddde;
		.goods-name{
			white-space: nowrap;
			overflow: hidden;
			text-overflow: ellipsis;
		}
	}
}
.history-box{
	padding: 0 5px;
	.history-title{
		display: flex;
		justify-content: space-between;
		align-items: center;
		height: 30rpx;
		font-size: 13px;
		padding: 13px 0;
		border-bottom: 1px solid #e0e3e9;
	}
	.history-list{
		display: flex;
		flex-wrap: wrap;
		.uni-tag{
			margin-top: 5px;
			margin-right: 5px;
			background-color: #efefef;
			color: #3A3A3A;
		}
	}
}
</style>
